class Comment {
  final int? id;
  final int postId;
  final int? userId;
  final String userName;
  final String? avatarUrl;
  final String content;
  final String? createTime;

  Comment({
    this.id,
    required this.postId,
    this.userId,
    required this.userName,
    this.avatarUrl,
    required this.content,
    this.createTime,
  });

  factory Comment.fromJson(Map<String, dynamic> json) {
    return Comment(
      id: _commentAsInt(json['id']),
      postId: _commentAsInt(json['postId']) ?? 0,
      userId: _commentAsInt(json['userId']),
      userName: _commentAsString(json['userName'] ?? json['author'], '匿名') ?? '匿名',
      avatarUrl: _commentAsString(json['avatarUrl']),
      content: _commentAsString(json['content'], '') ?? '',
      createTime: _commentAsString(json['createTime'] ?? json['createdTime']),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      if (id != null) 'id': id,
      'postId': postId,
      if (userId != null) 'userId': userId,
      'userName': userName,
      if (avatarUrl != null && avatarUrl!.isNotEmpty) 'avatarUrl': avatarUrl,
      'content': content,
      if (createTime != null) 'createTime': createTime,
    };
  }
}

// 辅助函数，使用不同的名称避免与 posts.dart 中的函数冲突
int? _commentAsInt(Object? v) {
  if (v == null) return null;
  if (v is int) return v;
  if (v is String) return int.tryParse(v);
  return null;
}

String? _commentAsString(Object? v, [String? defaultValue]) {
  if (v == null) return defaultValue;
  return v.toString();
}

